using System;
using System.Web;
using System.Web.Routing;
using System.Web.Mvc;

namespace Kollektiv.Web.Mvc
{
    public class MvcHandler : IHttpHandler
    {
        private string routeID;
        public RequestContext RequestContext { get; private set; }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }

        public MvcHandler(RequestContext requestContext, string routeID)
        {
            this.RequestContext = requestContext;
            this.routeID = routeID;
        }

        public void ProcessRequest(HttpContext context)
        {
            string routeOverride = RouteService.GetOverride(((this.RequestContext.HttpContext).Request).Path);
            if (!string.IsNullOrEmpty(routeOverride))
            {
                string url = UrlHelper.GenerateContentUrl(routeOverride, this.RequestContext.HttpContext);
                context.Response.Redirect(url, false);
            }
            else
            {
                if (string.IsNullOrEmpty(this.routeID))
                {
                    RouteService.MainInstance.ProcessRequest(this.RequestContext, context);
                }
                else
                {
                    RouteService.GetInstance(this.routeID).ProcessRequest(this.RequestContext, context);
                }
            }
        }
    }
}

